package net.qhzw.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.admin.component.FileTemplate;
import net.qhzw.admin.entity.Personnel;
import net.qhzw.admin.entity.PersonnelLog;
import net.qhzw.admin.mapper.PersonnelLogMapper;
import net.qhzw.admin.mapper.PersonnelMapper;
import net.qhzw.admin.mapper.SysDictMapper;
import net.qhzw.admin.param.PersonnelParam;
import net.qhzw.admin.pojo.PersonnelVo;
import net.qhzw.admin.query.PersonnelQuery;
import net.qhzw.admin.query.SelectQuery;
import net.qhzw.admin.service.PersonnelService;
import net.qhzw.common.model.JsonResult;
import net.qhzw.common.util.StringUtils;
import net.qhzw.common.util.UUIDUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class PersonnelServiceImpl implements PersonnelService {

    @Autowired
    private PersonnelMapper personnelMapper;

    @Autowired
    private PersonnelLogMapper personnelLogMapper;

    @Autowired
    private SysDictMapper dictMapper;

    @Autowired
    private FileTemplate fileTemplate;

    @Value("${config.imgage.view}")
    private String imageView;


    /***
     * 获取人员列表
     * @param query
     * @return
     */
    @Override
    public JsonResult getPersonnelList(PersonnelQuery query) {
        Map<String, Object> result = new HashMap<>();
        PageHelper.startPage(query.getPage(), query.getLimit());
        List<PersonnelVo> personnelVos = personnelMapper.selectList(query);
        for (PersonnelVo personnelVo : personnelVos) {
            if (personnelVo.getPhoto() != null && !StringUtils.isEmpty(personnelVo.getPhoto())) {
                personnelVo.setPhoto(imageView + personnelVo.getPhoto());
                String jsonString = JSON.toJSONString(personnelVo);
                log.info("jsonString: {}", jsonString.length());
            }
        }
        PageInfo<PersonnelVo> pageInfo = new PageInfo<>(personnelVos);
        result.put("total", pageInfo.getTotal());
        result.put("list", pageInfo.getList());
        return JsonResult.success(result);
    }


    /***
     * 新增人员
     * @param param
     * @param file
     * @return
     */
    @Override
    public JsonResult addToPersonnel(PersonnelParam param, MultipartFile file) {
        try {
            String upload = "";
            if (file != null && !file.isEmpty()) {
                upload = fileTemplate.upload(file);
            }
            if (param.getId() == null || StringUtils.isEmpty(param.getId())) {
                //新增
                Personnel personnel = new Personnel();
                BeanUtils.copyProperties(param, personnel);
                personnel.setId(UUIDUtil.getUUid());
                if (upload != null && !StringUtils.isEmpty(upload)) {
                    personnel.setPhoto(upload);
                }
                int row = personnelMapper.insertSelective(personnel);
                return result(row, "ERROR");
            }
            //修改
            PersonnelLog personnelLog = new PersonnelLog();
            PersonnelVo personnel = personnelMapper.selectPersonnelByKey(param.getId());
            PersonnelVo personnelAfter = new PersonnelVo();
            BeanUtils.copyProperties(param, personnelAfter);
            //设置名族名称
            if (param.getNation() != null && !StringUtils.isEmpty(param.getNation())) {
                String name = dictMapper.selectByName(new SelectQuery(param.getNation(), "sys_dict"));
                personnelAfter.setNationName(name);
            }
            //设置所属机构名称
            if (param.getMechanism() != null && !StringUtils.isEmpty(param.getMechanism())) {
                String name = dictMapper.selectByName(new SelectQuery(param.getMechanism(), "sys_mechanism"));
                personnelAfter.setMechanismName(name);
            }
            //设置教职身份
            if (param.getFacultyIdentity() != null && !StringUtils.isEmpty(param.getFacultyIdentity())) {
                String name = dictMapper.selectByName(new SelectQuery(param.getFacultyIdentity(), "sys_dict"));
                personnelAfter.setFacultyName(name);
            }
            if (upload != null && !StringUtils.isEmpty(upload)) {
                param.setPhoto(upload);
            }
            personnelLog.setActn("UPDATE");
            personnelLog.setId(UUIDUtil.getUUid());
            //操作者
            personnelLog.setOperator("3");
            personnelLog.setRecordTime(new Date());
            personnelLog.setOperatorObj(param.getId());
            //设置修改之前对象
            if (personnel.getPhoto() != null && !StringUtils.isEmpty(personnel.getPhoto())) {
                personnel.setPhoto(personnel.getPhoto());
            }
            String jsonString = JSON.toJSONString(personnel);
            personnelLog.setRecordBefore(jsonString);
            //设置修改之后对象 设置头像
            if (param.getPhoto() == null || StringUtils.isEmpty(param.getPhoto())) {
                if (upload != null) {
                    personnelAfter.setPhoto(upload);
                }
            } else {
                String[] split = param.getPhoto().split("/");
                personnelAfter.setPhoto(split[split.length - 1]);
            }
            personnelLog.setRecordAfter(JSON.toJSONString(personnelAfter));
            personnelLogMapper.insertSelective(personnelLog);
            //修改操作
            Personnel personnelNew = new Personnel();
            BeanUtils.copyProperties(param, personnelNew);
            if (param.getPhoto() != null && !StringUtils.isEmpty(param.getPhoto())) {
                String[] split = param.getPhoto().split("/");
                personnelNew.setPhoto(split[split.length - 1]);
            }
            int row = personnelMapper.updateByPrimaryKeySelective(personnelNew);
            return result(row, "ERROR");
        } catch (Exception e) {
            System.out.println("err:" + e.getMessage());
            return JsonResult.error("ERROR");
        }

    }


    /***
     * 删除人员
     * @param id
     * @return
     */
    @Transactional
    @Override
    public JsonResult deletePersonnel(String id) {
        PersonnelLog personnelLog = new PersonnelLog();
        personnelLog.setId(UUIDUtil.getUUid());
        personnelLog.setOperatorObj(id);
        //操作者id
        personnelLog.setOperator("3");
        personnelLog.setRecordTime(new Date());
        personnelLog.setActn("DELETE");
        personnelLogMapper.insertSelective(personnelLog);
        int row = personnelMapper.deleteByPrimaryKey(id);
        return result(row, "ERROR");
    }


    /***
     * 获取当前人员
     * @param id
     * @return
     */
    @Override
    public JsonResult getPersonnel(String id) {
        Personnel personnel = personnelMapper.selectByPrimaryKey(id);
        if (personnel.getPhoto() != null && !StringUtils.isEmpty(personnel.getPhoto())) {
            personnel.setPhoto(imageView + personnel.getPhoto());
        }
        return JsonResult.success(personnel);
    }


    /***
     * 判断修改数据库返回值 返回
     * @param row
     * @param msg
     * @return
     */
    private JsonResult result(int row, String msg) {
        if (row > 0) {
            return JsonResult.success();
        }
        return JsonResult.error(null, msg);
    }
}
